package com.example.netty.io.dispatcher

import com.example.netty.io.core.IMessageListener
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import io.netty.channel.Channel
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type

/**
 * File Name :JsonMessageDispatcher
 * Author : qihualu
 * Date : 2024/4/19
 * Desc :
 **/

abstract class JsonMessageDispatcher<T> : IMessageListener {
    companion object {
        private const val TAG = "JsonMessageDispatcher"
    }

    override fun onMessageArrived(channel: Channel, message: String) {
        val type = getType()
        val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
        val adapter = moshi.adapter<T>(type)
        val pojo = adapter.fromJson(message)
        onReceiveJsonObject(pojo = pojo)
    }

    private fun getType(): Type {
        val parameterizedType = this.javaClass.genericSuperclass as ParameterizedType
        val typeArgs = parameterizedType.actualTypeArguments
        return typeArgs[0]
    }

    abstract fun onReceiveJsonObject(pojo: T?)

}